package com.hk.kindheartedness;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.hk.kindheartedness.db.DBOpenHelper;
import com.hk.kindheartedness.util.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 处理患者挂号缴费业务
 */
public class PatientRegistrationActivity extends AppCompatActivity {

    //    Initialize Toast
    private Toast toast;

    //    Initialize intent
    private Intent intent;

    //    定义一个常量，记录两次点击后退按钮的时间差
    private Long exitTime = 0L;

    //    声明DBOpenHelper对象
    private DBOpenHelper dbOpenHelper;

    //    Initialize ListView
    private ListView queryDepartmentsListView;

    private ImageButton getBackBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_patient_registration);
//        实例化
        dbOpenHelper = new DBOpenHelper(PatientRegistrationActivity.this, "db_kindheartedness", null, 1);
//        获取ListView控制权
        queryDepartmentsListView = findViewById(R.id.queryDepartmentsListView);
//        获取返回按钮控制权
        getBackBtn = findViewById(R.id.getBackBtn);
        // TODO: 2022/3/20 编写查询一级科室
        /**
         * 查询出所有的一级科室并进行回显
         */
        findAllOneDepartments();
        //  2、通过一级查询二级科室，并进行回显
        queryDepartmentsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                获取选项中的HashMap对象
                HashMap<String, String> map = (HashMap<String, String>) queryDepartmentsListView.getItemAtPosition(position);
                String name = map.get("name");
                Log.i("获取的值为:{}",name);
//                2.1、通过一级科室查询是否具有二级科室，有，则进行回显，没有则进行下一步
                int findStatus = findByNameTwoDepartments(name);
                Log.i("科室Id为", String.valueOf(findStatus));
//              3、通过保存科室ID，查询当天日期的后三天日期，并显示到页面
                if (findStatus != 0) { // 最终科室Id
                    //        提取出传递的登录Id
                    Intent intent2 = getIntent();
                    Bundle bundle = intent2.getExtras();
                    bundle.putString("departmentsId",String.valueOf(findStatus));
                    bundle.putString("departmentsName",name);
                    intent = new Intent(PatientRegistrationActivity.this,PatientSubscribeActivity.class);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }


            }
        });
        //  4、点击预约日期，通过日期和科室查询当天是否有医生，点击医生进行挂号缴费预约


    }

    /**
     * 通过一级科室名称查询是否具有二级科室
     * @param name 科室名称
     * @return 是否存在，不存在则返回当前科室ID
     */
    private int findByNameTwoDepartments(String name) {
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
//        查询一级科室ID
        Cursor queryDepartments = readableDatabase.query("departments", null, "name = ?", new String[]{name}, null, null, null, null);
        String departmentsId = null;
        while (queryDepartments.moveToNext()) {
            departmentsId = queryDepartments.getString(0);
        }
        if (departmentsId == null) {
            toast = ToastUtil.toastHint(toast, PatientRegistrationActivity.this, "当前科室不存在，请重新查看！");
        }
//        通过科室ID查询所属二级科室
        Cursor queryDepartments2 = readableDatabase.query("departments", null, "departments_id != ? and departments_id = ?", new String[]{"0",departmentsId}, null, null, null, null);
        //        存储获取到的数据
        ArrayList<Map<String, Object>> resultList = new ArrayList<>();
        while (queryDepartments2.moveToNext()) {
            Map<String, Object> map = new HashMap<>(8);
            String name2 = queryDepartments2.getString(1);
//                对数据进行封装
            map.put("name", name2);
//                将封装的map集合存储到resulList集合中
            resultList.add(map);
        }
        //        判断是否具有科室
        if (resultList == null || resultList.size() == 0) {
//            toast = ToastUtil.toastHint(toast, PatientRegistrationActivity.this, "没有所属科室！"+"当前科室ID为"+departmentsId);
            return Integer.parseInt(departmentsId);
        }
        SimpleAdapter simpleAdapter = new SimpleAdapter(
                PatientRegistrationActivity.this,
                resultList,
                R.layout.query_department,
                new String[]{
                        "name"
                },
                new int[]{
                        R.id.departmentsName2
                }
        );
        queryDepartmentsListView.setAdapter(simpleAdapter);
//        android:background="@mipmap/get_back" 返回按钮设置背景颜色
        getBackBtn.setBackground(getResources().getDrawable(R.mipmap.get_back));
        getBackBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.getBackBtn:
//                        返回一级科室
                        findAllOneDepartments();
                        break;
                    default:
                        return;
                }
            }
        });
        return 0;
    }

    /**
     * 查询出所有一级科室并进行回显
     */
    private void findAllOneDepartments() {
//        打开数据库（获取数据库连接）
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
        Cursor queryDepartments = readableDatabase.query("departments", null, "departments_id = ?", new String[]{"0"}, null, null, null, null);
        //        存储获取到的数据
        ArrayList<Map<String, Object>> resultList = new ArrayList<>();
        while (queryDepartments.moveToNext()) {
            Map<String, Object> map = new HashMap<>(8);
            String name = queryDepartments.getString(1);
//                对数据进行封装
            map.put("name", name);
//                将封装的map集合存储到resulList集合中
            resultList.add(map);
        }
        //        判断是否具有科室
        if (resultList == null || resultList.size() == 0) {
            toast = ToastUtil.toastHint(toast, PatientRegistrationActivity.this, "暂时没有科室，请稍后查看！");
            return;
        }
        SimpleAdapter simpleAdapter = new SimpleAdapter(
                PatientRegistrationActivity.this,
                resultList,
                R.layout.query_department,
                new String[]{
                        "name"
                },
                new int[]{
                        R.id.departmentsName2
                }
        );
        queryDepartmentsListView.setAdapter(simpleAdapter);
//        修改返回按钮颜色为背景蓝色
        getBackBtn.setBackground(getResources().getDrawable(R.color.colorBlue));
    }

    //    重写onKeyDown()方法来拦截用户单击后退按钮事件
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        判断按下的是否为后退按键
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    //    创建退出方法
    private void exit() {
//        判断两次点击的时间差 大于2秒钟
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            toast = ToastUtil.toastHint(this.toast, PatientRegistrationActivity.this, "再按一次退出程序！");
            exitTime = System.currentTimeMillis();
        } else {
//            关闭当前Activity
            finish();
//            关闭程序
            System.exit(0);
        }
    }

    /**
     * 断开数据库连接
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dbOpenHelper != null) {
            dbOpenHelper.close();
        }
    }

}